package com.situ.mall.controller.back;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.situ.mall.util.JSONResult;

@Controller
@RequestMapping("/upload")
public class UploadController {

	@ResponseBody
	@RequestMapping("/uploadImage")
	public JSONResult uploadImage(MultipartFile file) {
		// 为了防止文件重名情况下覆盖原来的文件，所以生成一个不重复的随机的名字
		String name = UUID.randomUUID().toString().replace("-", "");
		String fileName = file.getOriginalFilename();
		System.out.println(fileName);// aa.jpg
		String extension = FilenameUtils.getExtension(fileName);// jpg
		String newFileName = name + "." + extension; // ce027287891449ebb74842baab5fc58d.jpg
		
		String filePath = "D:\\pic\\" + newFileName;
		try {
			file.transferTo(new File(filePath));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return JSONResult.ok("上传成功", newFileName);
	}
	
	public static void main(String[] args) {
		String uuid = UUID.randomUUID().toString();
		System.out.println(uuid);// 72b1afe5-a89b-4fce-bcab-fc4651362bd0
		System.out.println(uuid.replace("-", ""));// ce027287891449ebb74842baab5fc58d
	}
}
